package dubbo.server2.impl.common;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by yangxx on 2017/8/7 0007.
 */
public class FastDFSClient {
    private static final String CONFIG_FILENAME = "fdfs_client.conf";
    private static StorageClient1 storageClient1 = null;
    private static FastDFSClient fastDFSClient = null;
    private static Logger logger = Logger.getLogger(FastDFSClient.class);

    private FastDFSClient() {
        try {
            ClientGlobal.init(CONFIG_FILENAME);
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
            TrackerServer trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                logger.error("getConnection return null");
                throw new IllegalStateException("getConnection return null");
            }

            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            if (storageServer == null) {
                logger.error("getStoreStorage return null");
                throw new IllegalStateException("getStoreStorage return null");
            }

            storageClient1 = new StorageClient1(trackerServer, storageServer);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public static FastDFSClient getInstance() {
        if (fastDFSClient == null) {
            synchronized (FastDFSClient.class) {
                if (fastDFSClient == null) {
                    fastDFSClient = new FastDFSClient();
                }
            }
        }
        return fastDFSClient;
    }

    /**
     * 上传文件
     *
     * @param file     文件对象
     * @param fileName 文件名
     * @return
     */
    public String uploadFile(File file, String fileName) {
        return uploadFile(file, fileName, null);
    }

    /**
     * 上传文件
     *
     * @param file     文件对象
     * @param fileName 文件名
     * @param metaList 文件元数据
     * @return
     */
    public String uploadFile(File file, String fileName, Map<String, String> metaList) {
        try {
            byte[] buff = IOUtils.toByteArray(new FileInputStream(file));
            return uploadFile(buff, fileName, metaList);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    public String uploadFile(byte[] buff, String fileName) {
        return uploadFile(buff, fileName, null);
    }


    public String uploadFile(byte[] buff, String fileName, Map<String, String> metaList) {
        try {
            NameValuePair[] nameValuePairs = null;
            if (metaList != null) {
                nameValuePairs = new NameValuePair[metaList.size()];
                int index = 0;
                for (Iterator<Map.Entry<String, String>> iterator = metaList.entrySet().iterator(); iterator.hasNext(); ) {
                    Map.Entry<String, String> entry = iterator.next();
                    String name = entry.getKey();
                    String value = entry.getValue();
                    nameValuePairs[index++] = new NameValuePair(name, value);
                }
            }
            return storageClient1.upload_file1(buff, FilenameUtils.getExtension(fileName), nameValuePairs);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 获取文件元数据
     *
     * @param fileId 文件ID
     * @return
     */
    public Map<String, String> getFileMetadata(String fileId) {
        try {
            NameValuePair[] metaList = storageClient1.get_metadata1(fileId);
            if (metaList != null) {
                HashMap<String, String> map = new HashMap<String, String>();
                for (NameValuePair metaItem : metaList) {
                    map.put(metaItem.getName(), metaItem.getValue());
                }
                return map;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param fileId 文件ID
     * @return 删除失败返回-1，否则返回0
     */
    public int deleteFile(String fileId) {
        try {
            return storageClient1.delete_file1(fileId);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return -1;
    }

    /**
     * 下载文件
     *
     * @param fileId  文件ID（上传文件成功后返回的ID）
     * @param outFile 文件下载保存位置
     * @return
     */
    public int downloadFile(String fileId, File outFile) {
        FileOutputStream fos = null;
        try {
            byte[] content = storageClient1.download_file1(fileId);
            if (content != null) {
                fos = new FileOutputStream(outFile);
                IOUtils.write(content, fos);
                return 0;
            } else {
                return -1;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return -1;
    }

    public byte[] downloadFile(String fileId) {
        try {
            byte[] content = storageClient1.download_file1(fileId);
            return content;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

   /* public static void main(String[] args) {
        String path = FastDFSClient.getInstance().uploadFile(new File("f://read.html"),"read.html");
        System.out.println("==============="+path);
    }*/
}
